package com.ad.aidai.fragments.register;

import android.content.Context;
import android.content.SharedPreferences;

import com.ad.aidai.bean.User;
import com.ad.aidai.common.ADApp;
import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.common.utils.EncryptUtils;
import com.ad.aidai.db.dao.MyUserDao;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.RegisterResultFromNet;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import cn.smssdk.SMSSDK;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

import static android.content.Context.MODE_PRIVATE;

/**
 * RegisterPresenter
 * <p>
 * Created by Yusxon on 16/12/7.
 */

public class RegisterPresenter implements RegisterContract.Presenter {

    private Context mContext;
    private RegisterContract.View mView;
    private CompositeSubscription mSubscriptions;
    private SharedPreferences aidaiSP;
    private boolean setCode = false;


    public RegisterPresenter(Context context, RegisterContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
        aidaiSP = mContext.getSharedPreferences("AIDAI", MODE_PRIVATE);
    }

    @Override
    public void subscribe() {
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
        mSubscriptions.clear();
        mSubscriptions = null;
    }

    @Override
    public void sendVerificationCode(final String phoneNumber) {
        if (CheckUtil.checkStrNull(phoneNumber)) {
            if (mView != null) {
                mView.toast("请输入手机号");
            }
        } else if (!CheckUtil.checkPhone(phoneNumber)) {
            if (mView != null) {
                mView.toast("手机号格式不正确");
            }
        } else {
            if (mView != null) {
                mView.setVCButtonClickable(false);
            }
            Subscription subscription = Observable
                    .create(new Observable.OnSubscribe<Object>() {
                        @Override
                        public void call(Subscriber<? super Object> subscriber) {
                            SMSSDK.getVerificationCode("86", phoneNumber);
                            setCode = true;
                            for (int i = 59; setCode && i >= 0; --i) {
                                if (mView != null) {
                                    try {
                                        Thread.sleep(1000);
                                        if(setCode) {
                                            subscriber.onNext(i);
                                        }
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    break;
                                }
                            }
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Object>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            MobclickAgent.reportError(mContext, e);
                            if (mView != null) {
                                Logger.t("RegisterPresenter").e(e.getMessage());
                                mView.toast("获取验证码失败");
                                setCode = false;
                                mView.setVCButtonClickable(true);
                            }
                        }

                        @Override
                        public void onNext(Object o) {
                            if (o instanceof Integer) {
                                if (mView != null) {
                                    mView.showVerficationCodeCountDown("(" + o + "s)后可重发");
                                    if ((int) o == 0) {
                                        setCode = false;
                                        mView.setVCButtonClickable(true);
                                    }
                                }
                            }
                        }
                    });
            mSubscriptions.add(subscription);
        }
    }

    private String passwordMD5;

    @Override
    public void register(final String phoneNumber, String password, String verficationCode) {
        if (CheckUtil.checkStrNull(phoneNumber) || CheckUtil.checkStrNull(password) || CheckUtil.checkStrNull
                (verficationCode)) {
            if (mView != null) {
                mView.toast("手机号、密码和验证码不能为空");
            }
        } else if (!CheckUtil.checkPhone(phoneNumber)) {
            if (mView != null) {
                mView.toast("手机号格式不正确");
            }
        } else {
            //显示加载对话框
            if (mView != null) {
                mView.showLoading();
            }
            passwordMD5 = EncryptUtils.GetMD5Code(password);
            Logger.t(this.getClass().getSimpleName()).i(passwordMD5);
            NetWork.getAccountOperationApi()
                    .register(phoneNumber, passwordMD5, verficationCode)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<RegisterResultFromNet>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            MobclickAgent.reportError(mContext, e);
                            if (mView != null) {
                                Logger.t("LoginPresenter").e(e.getMessage());
                                //关闭加载对话框
                                mView.closeLoading(false);
                                mView.toast("注册失败");
                                setCode = false;
                                mView.setVCButtonClickable(true);
                            }
                        }

                        @Override
                        public void onNext(RegisterResultFromNet registerResultFromNet) {
                            Logger.t("RegisterPresenter").i(registerResultFromNet.toString());
                            setCode = false;
                            mView.setVCButtonClickable(true);
                            if (mView != null) {
                                if (registerResultFromNet.getCode() != StatusCodeFromNet.CODE_SUCCESS) {
                                    mView.closeLoading(false);
                                    dealErrorCode(registerResultFromNet.getCode());
                                    Logger.t("RegisterPresenter").i(registerResultFromNet.toString());
                                } else {
                                    saveUserInfo(registerResultFromNet.getData(), phoneNumber, passwordMD5);
                                    mView.closeLoading(true);
                                    mView.registerSuccess();
                                }
                            }
                        }
                    });
        }
    }

    /**
     * 保存用户信息
     *
     * @param user     用户
     * @param phone    手机号
     * @param password 密码
     */
    private void saveUserInfo(User user, String phone, String password) {
        user.setUserIcon("0.jpg");
        user.setUserSex(0);
        user.setUserPayNum("");
        user.setUserPersonalNote("");
        MyUserDao.getUserDao().deleteAll();
        MyUserDao.getUserDao().insert(user);
        ADApp.setUser();
        aidaiSP.edit()
                .putBoolean("IS_LOGIN", true)
                .putString("USER_PHONE", phone)
                .putString("USER_PASSWORD", password)
                .apply();
    }

    /**
     * 处理错误码信息
     *
     * @param code 错误码
     */
    private void dealErrorCode(int code) {
        if (mView != null) {
            switch (code) {
                case StatusCodeFromNet.CODE_SERVER_EXCEPTION:
                    mView.toast("注册失败,服务器异常");
                    break;
                case StatusCodeFromNet.CODE_PHONE_EXIST:
                    mView.toast("该手机号已注册过");
                    break;
                case StatusCodeFromNet.CODE_VC_ERROR:
                    mView.toast("验证码错误");
                    break;
                default:
                    mView.toast("注册失败");
                    break;
            }
        }
    }
}
